[LeetCode] 513 - Find Bottom Left Tree Value

題意

找出樹中最下層且最左邊的元素。

解法

BFS。

程式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var findBottomLeftValue = function(root) {
if ( !root ) return 0;
let queue = [root];
let result = 0;
while( queue.length !== 0 ){
let length = queue.length;
for ( let i = 0; i < length; i ++ ){
let node = queue.shift();
if ( i === 0 ) result = node.val;
if ( node.left ) queue.push(node.left);
if ( node.right ) queue.push(node.right);
}
}
return result;
};